package com.ruoyi.system.service.impl;

import java.util.*;
import java.util.stream.Collectors;

import javax.persistence.criteria.Predicate;

import com.ruoyi.common.core.redis.RedisCache;
import com.ruoyi.system.dao.SysUserDAO;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Sort;
import org.springframework.data.jpa.domain.Specification;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import com.ruoyi.common.constant.Constants;
import com.ruoyi.common.constant.UserConstants;
import com.ruoyi.common.core.domain.TreeSelect;
import com.ruoyi.common.core.domain.entity.SysMenu;
import com.ruoyi.common.core.domain.entity.SysRole;
import com.ruoyi.common.core.domain.entity.SysUser;
import com.ruoyi.common.dao.service.BaseAppDAO;
import com.ruoyi.common.utils.SecurityUtils;
import com.ruoyi.common.utils.StringUtils;
import com.ruoyi.system.dao.SysMenuDAO;
import com.ruoyi.system.dao.SysRoleDAO;
import com.ruoyi.system.domain.vo.MetaVo;
import com.ruoyi.system.domain.vo.RouterVo;
import com.ruoyi.system.service.ISysMenuService;

/**
 * 菜单 业务层处理
 *
 * @author ruoyi
 */
@Service
public class SysMenuServiceImpl implements ISysMenuService {
    public static final String PREMISSION_STRING = "perms[\"{0}\"]";

    @Autowired
    private BaseAppDAO baseDAO;

    @Autowired
    private SysMenuDAO menuDAO;

    @Autowired
    private SysRoleDAO roleDAO;

    @Autowired
    private RedisCache redisCache;

    @Autowired
    private SysUserDAO userDAO;

    /**
     * 根据用户查询系统菜单列表
     *
     * @param userId 用户ID
     * @return 菜单列表
     */
    @Override
    public List<SysMenu> selectMenuList(String userId, boolean ishasAction) {
        return selectMenuList(new SysMenu(), userId, ishasAction);
    }

    /**
     * 查询系统菜单列表
     *
     * @param menu 菜单信息
     * @return 菜单列表
     */
    @Override
    public List<SysMenu> selectMenuList(SysMenu menu, String userId, boolean ishasAction) {
        List<SysMenu> menuList = null;
        SysUser user = userDAO.findById(userId).orElse(null);
        // 管理员显示所有菜单信息
        if (SysUser.isAdmin(user.getUserName())) {
            menuList = selectMenuList(menu, ishasAction);
        } else {
            menuList = selectMenuListByUserId(userId, user.getUserName(), ishasAction);
        }
        return menuList;
    }

    /**
     * 根据用户ID查询权限
     *
     * @param userId 用户ID
     * @return 权限列表
     */
    @SuppressWarnings("unchecked")
    @Override
    public Set<String> selectMenuPermsByUserId(String userId) {
        List<String> perms = menuDAO.selectMenuPermsByUserId(userId);
        Set<String> permsSet = new HashSet<>();
        for (String perm : perms) {
            if (StringUtils.isNotEmpty(perm)) {
                permsSet.addAll(Arrays.asList(perm.trim().split(",")));
            }
        }
        return permsSet;
    }

    /**
     * 根据用户ID查询菜单
     *
     * @param userId 用户名称
     * @return 菜单列表
     */
    @SuppressWarnings("unchecked")
    @Override
    public List<SysMenu> selectMenuTreeByUserId(String userId) {
        SysUser user = userDAO.findById(userId).orElse(null);
        List<SysMenu> menus = null;
        if (SecurityUtils.isAdmin(user.getUserName())) {
            String querysql = " select distinct m.menu_id, m.parent_id, m.menu_name,"
                    + " m.path, m.component, m.`query`, m.visible, m.status, ifnull(m.perms,'') as perms, "
                    + " m.is_frame, m.is_cache, m.menu_type, m.icon, m.order_num, m.create_time, "
                    + " m.create_by, m.update_by, m.update_time,m.remark from sys_menu m "
                    + "where m.menu_type in ('M', 'C') and m.status = 0	order by m.parent_id, m.order_num";
            menus = baseDAO.createNativeQuery(querysql, SysMenu.class);
        } else {
            String querysql = " select distinct m.menu_id, m.parent_id, m.menu_name, m.path, m.component,"
                    + " m.`query`, m.visible, m.status, ifnull(m.perms,'') as perms, m.is_frame, m.is_cache, "
                    + " m.menu_type, m.icon, m.order_num, m.create_time,m.create_by, m.update_by, m.update_time,m.remark "
                    + " from sys_menu m	 "
                    + " left join sys_post_menu pm on m.menu_id = pm.menu_id "
                    + " left join sys_post po on po.post_id = pm.post_id "
                    + " left join sys_role_post rp on pm.post_id = rp.post_id	"
                    + " left join sys_role ro on rp.role_id = ro.role_id "
                    + " left join sys_role_user ru on ru.role_id = ru.role_id "
                    + " where ru.user_id = '" + userId + "' and m.menu_type in ('M', 'C') and po.status = 0 "
                    + " and m.status = 0  AND ro.status = 0	order by m.parent_id, m.order_num";
            menus = baseDAO.createNativeQuery(querysql, SysMenu.class);
        }
        return getChildPerms(menus, "0");
    }

    /**
     * 根据角色ID查询菜单树信息
     *
     * @param roleId 角色ID
     * @return 选中菜单列表
     */
    @Override
    public List<Long> selectMenuListByRoleId(String roleId) {
        SysRole role = roleDAO.getById(roleId);


        String querysql = " select m.menu_id from sys_menu m "
                + " left join sys_role_menu rm on m.menu_id = rm.menu_id "
                + " where rm.role_id = " + roleId;

        if (role.isMenuCheckStrictly()) {
            querysql += " and m.menu_id not in (select m.parent_id from sys_menu m "
                    + "inner join sys_role_menu rm on m.menu_id = rm.menu_id and rm.role_id = " + roleId + ") ";
        }
        querysql += " order by m.parent_id, m.order_num ";
        //menuDAO.selectMenuListByRoleId(roleId, role.isMenuCheckStrictly())
        return baseDAO.createNativeQuery(querysql);
    }

    /**
     * 构建前端路由所需要的菜单
     *
     * @param menus 菜单列表
     * @return 路由列表
     */
    @Override
    public List<RouterVo> buildMenus(List<SysMenu> menus) {
        List<RouterVo> routers = new LinkedList<RouterVo>();
        for (SysMenu menu : menus) {
            RouterVo router = new RouterVo();
            router.setHidden("1".equals(menu.getVisible()));//0 显示  1隐藏
            router.setName(getRouteName(menu));
            router.setPath(getRouterPath(menu));
            router.setComponent(getComponent(menu));
            router.setQuery(menu.getQuery());
            router.setMeta(new MetaVo(menu.getMenuName(), menu.getIcon(), StringUtils.equals("1", menu.getIsCache()), menu.getPath()));
            List<SysMenu> cMenus = menu.getChildren();
            if (!cMenus.isEmpty() && cMenus.size() > 0 && UserConstants.TYPE_DIR.equals(menu.getMenuType())) {
                router.setAlwaysShow(true);
                router.setRedirect("noRedirect");
                router.setChildren(buildMenus(cMenus));
            } else if (isMenuFrame(menu)) {
//                router.setMeta(null);
                List<RouterVo> childrenList = new ArrayList<RouterVo>();
                RouterVo children = new RouterVo();
                children.setPath(menu.getPath());
                children.setComponent(menu.getPath());
                children.setName(StringUtils.capitalize(menu.getPath()));
                children.setMeta(new MetaVo(menu.getMenuName(), menu.getIcon(), StringUtils.equals("1", menu.getIsCache()), menu.getPath()));
                children.setQuery(menu.getQuery());
                childrenList.add(children);
                router.setChildren(childrenList);
            } else if (menu.getParentId().equals("0") && isInnerLink(menu)) {
                router.setMeta(new MetaVo(menu.getMenuName(), menu.getIcon()));
                router.setPath("/");
                List<RouterVo> childrenList = new ArrayList<RouterVo>();
                RouterVo children = new RouterVo();
                String routerPath = innerLinkReplaceEach(menu.getPath());
                children.setPath(routerPath);
                children.setComponent(UserConstants.INNER_LINK);
                children.setName(StringUtils.capitalize(routerPath));
                children.setMeta(new MetaVo(menu.getMenuName(), menu.getIcon(), menu.getPath()));
                childrenList.add(children);
                router.setChildren(childrenList);
            }
            routers.add(router);
        }
        return routers;
    }

    /**
     * 构建前端所需要树结构
     *
     * @param menus 菜单列表
     * @return 树结构列表
     */
    @Override
    public List<SysMenu> buildMenuTree(List<SysMenu> menus) {
        List<SysMenu> returnList = new ArrayList<SysMenu>();
        List<String> tempList = new ArrayList<String>();
        for (SysMenu dept : menus) {
            tempList.add(dept.getMenuId());
        }
        for (Iterator<SysMenu> iterator = menus.iterator(); iterator.hasNext(); ) {
            SysMenu menu = (SysMenu) iterator.next();
            // 如果是顶级节点, 遍历该父节点的所有子节点
            if (!tempList.contains(menu.getParentId())) {
                recursionFn(menus, menu);
                returnList.add(menu);
            }
        }
        if (returnList.isEmpty()) {
            returnList = menus;
        }
        return returnList;
    }

    /**
     * 构建前端所需要下拉树结构
     *
     * @param menus 菜单列表
     * @return 下拉树结构列表
     */
    @Override
    public List<TreeSelect> buildMenuTreeSelect(List<SysMenu> menus) {
        List<SysMenu> menuTrees = buildMenuTree(menus);
        return menuTrees.stream().map(TreeSelect::new).collect(Collectors.toList());
    }

    /**
     * 根据菜单ID查询信息
     *
     * @param menuId 菜单ID
     * @return 菜单信息
     */
    @Override
    @Transactional
    public SysMenu selectMenuById(String menuId) {

        return menuDAO.findById(menuId).orElse(null);
    }

    @Override
    public String selectMenuNameByPath(String userid, String path) {
        SysUser user = userDAO.findById(userid).orElse(null);
        List<SysMenu> menus = menus = this.selectMenuListByUserId(userid, user.getUserName(), false);
        if (path.startsWith("/")) {
            path = path.replaceFirst("/", "");
        }
        return getMenuName(menus, path);
    }


    private String getMenuName(List<SysMenu> menus, String path) {
        if (StringUtils.isNotEmpty(menus)) {
            for (SysMenu menu : menus) {
                if (StringUtils.isNotEmpty(menu.getPath()) && menu.getPath().equals(path)) {
                    return menu.getMenuName();
                }
                String name = getMenuName(menu.getChildren(), path);
                if (StringUtils.isNotEmpty(name)) {
                    return name;
                }
            }
        }
        return null;
    }

    @Override
    public List<SysMenu> selectMenuByParentId(String parentId) {
        SysMenu menu = new SysMenu();
        menu.setParentId(parentId);
        return selectMenuList(menu, true);
    }

    /**
     * 是否存在菜单子节点
     *
     * @param menuId 菜单ID
     * @return 结果
     */
    @Override
    public boolean hasChildByMenuId(String menuId) {
        Specification<SysMenu> specification = (root, criteriaQuery, criteriaBuilder) -> {
            Predicate redicate = criteriaBuilder.equal(root.get("parentId"), menuId);
            return criteriaBuilder.and(redicate);
        };
        long result = menuDAO.count(specification);
        return result > 0 ? true : false;
    }


    /**
     * 新增保存菜单信息
     *
     * @param menu 菜单信息
     * @return 结果
     */
    @Override
    @Transactional
    public int insertMenu(SysMenu menu) {
        menuDAO.save(menu);
        return 1;
    }

    /**
     * 修改保存菜单信息
     *
     * @param menu 菜单信息
     * @return 结果
     */
    @Override
    @Transactional
    public int updateMenu(SysMenu menu) {
        menuDAO.save(menu);
        return 1;
    }

    /**
     * 删除菜单管理信息
     *
     * @param menuId 菜单ID
     * @return 结果
     */
    @Override
    @Transactional
    public int deleteMenuById(String menuId) {
        menuDAO.deleteById(menuId);
        return 1;
    }

    /**
     * 校验菜单名称是否唯一
     *
     * @param menu 菜单信息
     * @return 结果
     */
    @Override
    public String checkMenuNameUnique(SysMenu menu) {
        String menuId = StringUtils.isNull(menu.getMenuId()) ? "" : menu.getMenuId();
        SysMenu info = menuDAO.findTop1ByMenuNameAndParentId(menu.getMenuName(), menu.getParentId());
        if (StringUtils.isNotNull(info) && !info.getMenuId().equals(menuId)) {
            return UserConstants.NOT_UNIQUE;
        }
        return UserConstants.UNIQUE;
    }

    /**
     * 获取路由名称
     *
     * @param menu 菜单信息
     * @return 路由名称
     */
    public String getRouteName(SysMenu menu) {
        String routerName = StringUtils.capitalize(menu.getPath());
        // 非外链并且是一级目录（类型为目录）
        if (isMenuFrame(menu)) {
            routerName = StringUtils.EMPTY;
        }
        return routerName;
    }

    /**
     * 获取路由地址
     *
     * @param menu 菜单信息
     * @return 路由地址
     */
    public String getRouterPath(SysMenu menu) {
        String routerPath = menu.getPath();
        // 内链打开外网方式
        if (!menu.getParentId().equals("0") && isInnerLink(menu)) {
            routerPath = innerLinkReplaceEach(routerPath);
        }
        // 非外链并且是一级目录（类型为目录）
        if (menu.getParentId().equals("0") && UserConstants.TYPE_DIR.equals(menu.getMenuType())
                && UserConstants.NO_FRAME.equals(menu.getIsFrame())) {
            routerPath = "/" + menu.getPath();
        }
        // 非外链并且是一级目录（类型为菜单）
        else if (isMenuFrame(menu)) {
            routerPath = "/";
        }
        return routerPath;
    }

    /**
     * 获取组件信息
     *
     * @param menu 菜单信息
     * @return 组件信息
     */
    public String getComponent(SysMenu menu) {
        String component = UserConstants.LAYOUT;
        if (StringUtils.isNotEmpty(menu.getPath()) && isMenuFrame(menu)) {
            component = menu.getPath();
        } else if (StringUtils.isEmpty(menu.getPath()) && !menu.getParentId().equals("0") && isInnerLink(menu)) {
            component = UserConstants.INNER_LINK;
        } else if (StringUtils.isNotEmpty(menu.getPath()) && isOuterLink(menu)) {
            component = UserConstants.OUTER_LINK;
        } else if (StringUtils.isEmpty(menu.getPath()) && isParentView(menu)) {
            component = UserConstants.PARENT_VIEW;
        }
        return component;
    }

    /**
     * 是否为菜单内部跳转
     *
     * @param menu 菜单信息
     * @return 结果
     */
    public boolean isMenuFrame(SysMenu menu) {
        return UserConstants.TYPE_MENU.equals(menu.getMenuType())//类型为菜单
                && menu.getIsFrame().equals(UserConstants.NO_FRAME);//  链接方式是非外链
    }

    /**
     * 是否为内链组件
     *
     * @param menu 菜单信息
     * @return 结果
     */
    public boolean isInnerLink(SysMenu menu) {
        return menu.getIsFrame().equals(UserConstants.NO_FRAME) && StringUtils.ishttp(menu.getPath());
    }


    /**
     * 是否为外部网络链接
     *
     * @param menu 菜单信息
     * @return 结果
     */
    public boolean isOuterLink(SysMenu menu) {
        return menu.getIsFrame().equals(UserConstants.YES_FRAME) && StringUtils.ishttp(menu.getPath());
    }

    /**
     * 是否为parent_view组件
     *
     * @param menu 菜单信息
     * @return 结果
     */
    public boolean isParentView(SysMenu menu) {
        return !menu.getParentId().equals("0") && UserConstants.TYPE_DIR.equals(menu.getMenuType());
    }

    /**
     * 根据父节点的ID获取所有子节点
     *
     * @param list     分类表
     * @param parentId 传入的父节点ID
     * @return String
     */
    public List<SysMenu> getChildPerms(List<SysMenu> list, String parentId) {
        List<SysMenu> returnList = new ArrayList<SysMenu>();
        for (Iterator<SysMenu> iterator = list.iterator(); iterator.hasNext(); ) {
            SysMenu t = (SysMenu) iterator.next();
            // 一、根据传入的某个父节点ID,遍历该父节点的所有子节点
            if (t.getParentId().equals(parentId)) {
                recursionFn(list, t);
                returnList.add(t);
            }
        }
        return returnList;
    }

    /**
     * 递归列表
     *
     * @param list
     * @param t
     */
    private void recursionFn(List<SysMenu> list, SysMenu t) {
        // 得到子节点列表
        List<SysMenu> childList = getChildList(list, t);
        t.setChildren(childList);
        for (SysMenu tChild : childList) {
            if (hasChild(list, tChild)) {
                recursionFn(list, tChild);
            }
        }
    }

    /**
     * 得到子节点列表
     */
    private List<SysMenu> getChildList(List<SysMenu> list, SysMenu t) {
        List<SysMenu> tlist = new ArrayList<SysMenu>();
        Iterator<SysMenu> it = list.iterator();
        while (it.hasNext()) {
            SysMenu n = (SysMenu) it.next();
            if (n.getParentId().equals(t.getMenuId())) {
                tlist.add(n);
            }
        }
        return tlist;
    }

    /**
     * 判断是否有子节点
     */
    private boolean hasChild(List<SysMenu> list, SysMenu t) {
        return getChildList(list, t).size() > 0;
    }

    /**
     * 内链域名特殊字符替换
     *
     * @return
     */
    public String innerLinkReplaceEach(String path) {
        return StringUtils.replaceEach(path, new String[]{Constants.HTTP, Constants.HTTPS},
                new String[]{"", ""});
    }

    @Override
    public List<SysMenu> selectMenuList(SysMenu sysmenu, boolean ishasAction) {
        Specification<SysMenu> specification = (root, criteriaQuery, criteriaBuilder) -> {
            List<Predicate> predicateList = new ArrayList<>();
            if (!StringUtils.isEmpty(sysmenu.getMenuName())) {
                predicateList.add(criteriaBuilder.equal(root.get("menuName"), sysmenu.getMenuName()));
            }

            if (!StringUtils.isEmpty(sysmenu.getVisible())) {
                predicateList.add(criteriaBuilder.equal(root.get("visible"), sysmenu.getVisible()));
            }

            if (!StringUtils.isEmpty(sysmenu.getStatus())) {
                predicateList.add(criteriaBuilder.equal(root.get("status"), sysmenu.getStatus()));
            }
            if (!StringUtils.isNull(sysmenu.getParentId())) {
                predicateList.add(criteriaBuilder.equal(root.get("parentId"), sysmenu.getParentId()));
            }
            if (!ishasAction) {//是否包含按钮数据
                predicateList.add(criteriaBuilder.notEqual(root.get("menuType"), "F"));
            }

            Predicate[] p = new Predicate[predicateList.size()];
            return criteriaBuilder.and(predicateList.toArray(p));
        };

        return menuDAO.findAll(specification, Sort.by("orderNum"));
    }

    @Override
    public List<SysMenu> selectMenuListByUserId(String userId, String userName, boolean ishasAction) {
        String querysql = "select distinct m.* from "
                + "sys_menu m where 1=1";
        if (!"admin".equals(userName)) {
            querysql += " and ur.user_id = " + userId;
        }

        if (!ishasAction) {
            querysql += " and m.menu_type <> 'F' ";
        }
        List list = baseDAO.createNativeQuery(querysql, SysMenu.class);
        return list;
    }
}
